<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="目录" prop="directory">
        <el-input
          v-model="queryParams.directory"
          placeholder="请输入目录"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="父id" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="isDel">
        <el-input
          v-model="queryParams.isDel"
          placeholder="请输入是否删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <TableCard>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['am:directory:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['am:directory:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini"
                     @click="handleLinkRoleDir" v-hasPermi="['am:role_directory:add']">配置角色权限</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-if="refreshTable" v-loading="loading"
                :data="amDirectoryList" row-key="id"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="目录" align="left" prop="directory" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['am:directory:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)" v-hasPermi="['am:directory:add']">新增</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['am:directory:remove']">删除</el-button>
<!--            <el-button size="mini" type="text" icon="el-icon-user" @click="handleLinkRole(scope.row)"-->
<!--                       v-hasPermi="['am:amFolder:remove']">关联角色</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </TableCard>
    <!-- 添加或修改目录管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级" prop="parentId">
          <treeselect v-model="form.parentId" :options="amDirectoryOptions"
                      :normalizer="normalizer" placeholder="请选择上级"/>
        </el-form-item>
        <el-form-item label="目录" prop="directory">
          <el-input v-model="form.directory" placeholder="请输入目录" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="是否删除" prop="isDel">-->
<!--          <el-input v-model="form.isDel" placeholder="请输入是否删除" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <ModalLinkRole ref="ModalLinkRoleRef"/>
    <ModalLinkRoleDir ref="ModalLinkRoleDirRef" />
  </div>
</template>

<script>
import { treeDirectory, listDirectory, getDirectory, delDirectory, addDirectory, updateDirectory } from "@/api/am/directory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ModalLinkRole from "./ModalLinkRole.vue";
import ModalLinkRoleDir from "./ModalLinkRoleDir.vue";

function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
    if(o[config.childrenList]) {
      o[config.childrenList] = o[config.childrenList].sort((a, b) => {
        // console.log(a, b);
        return a.sort - b.sort
      })
    }
  }
  return tree;
}

export default {
  name: "AmFolder",
  dicts: ['sys_normal_disable'],
  components: {
    ModalLinkRoleDir,
    ModalLinkRole,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 文件夹表格数据
      amDirectoryList: [],
      // 文件夹树选项
      amDirectoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 999,
        directory: null,
        parentId: null,
        sort: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleLinkRoleDir() {
      this.$refs.ModalLinkRoleDirRef.open();
    },
    handleLinkRole(row) {
      this.$refs.ModalLinkRoleRef.open(row);
    },
    /** 查询文件夹列表 */
    getList() {
      // treeDirectory()
      this.loading = true;
      listDirectory(this.queryParams).then(response => {
        this.amDirectoryList = handleTree(response.rows, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换文件夹数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.directory,
        children: node.children
      };
    },
    /** 查询文件夹下拉树结构 */
    getTreeselect(callback) {
      listDirectory(this.queryParams).then(response => {
        this.amDirectoryOptions = [];
        const data = {id: 0, directory: '顶级节点', children: []};
        data.children = handleTree(response.rows, "id", "parentId");
        this.amDirectoryOptions.push(data);
        this.$nextTick(() => {
          callback()
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        directory: null,
        parentId: null,
        sort: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect(() => {
        if (row != null && row.id) {
          this.form.parentId = row.id;
        } else {
          this.form.parentId = 0;
        }
        this.open = true;
        this.title = "添加目录管理";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.getTreeselect(() => {
        getDirectory(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改目录管理";
        });
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDirectory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDirectory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除目录管理编号为"' + ids + '"的数据项？').then(function() {
        return delDirectory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('am/directory/export', {
        ...this.queryParams
      }, `directory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
